package com.warmlight.voicepacket.network.cookie;


import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.cache.CookieCache;
import com.franmontiel.persistentcookiejar.persistence.CookiePersistor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

/**
 * Created by weiweijinpeng on 2018/1/28.
 * cookie管理
 */
public class CommonCookieJar implements ClearableCookieJar {

    private static CommonCookieJar mInstance;

    public static CommonCookieJar getInstance(){
        if(mInstance == null){
            synchronized (CommonCookieJar.class){
                if(mInstance == null){
                    mInstance = new CommonCookieJar();
                }
            }
        }
        return mInstance;
    }

    private CookieCache cookieCache;
    private CookiePersistor cookiePersistor;

    public CommonCookieJar setCookieCache(CookieCache cookieCache, CookiePersistor cookiePersistor){
        this.cookieCache = cookieCache;
        this.cookiePersistor = cookiePersistor;
        this.cookieCache.addAll(cookiePersistor.loadAll());
        return getInstance();
    }

    @Override
    synchronized public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        cookieCache.addAll(cookies);
        cookiePersistor.saveAll(filterPersistentCookies(cookies));
    }

    private static List<Cookie> filterPersistentCookies(List<Cookie> cookies) {
        List<Cookie> persistentCookies = new ArrayList<>();

        for (Cookie cookie : cookies) {
            if (cookie.persistent()) {
                persistentCookies.add(cookie);
            }
        }
        return persistentCookies;
    }

    @Override
    synchronized public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookiesToRemove = new ArrayList<>();
        List<Cookie> validCookies = new ArrayList<>();

        for (Iterator<Cookie> it = cookieCache.iterator(); it.hasNext(); ) {
            Cookie currentCookie = it.next();
            if (isCookieExpired(currentCookie)) {
                cookiesToRemove.add(currentCookie);
                it.remove();
            } else if (currentCookie.matches(url)) {
                validCookies.add(currentCookie);
            }
        }
        if(cookiesToRemove.size() > 0){
//            UserShared.getInstance().logout();
        }
        cookiePersistor.removeAll(cookiesToRemove);
        return validCookies;
    }

    private boolean isCookieExpired(Cookie cookie) {
        return cookie.expiresAt() < System.currentTimeMillis();
    }

    @Override
    synchronized public void clearSession() {
        cookieCache.clear();
        cookieCache.addAll(cookiePersistor.loadAll());
    }

    @Override
    synchronized public void clear() {
        cookieCache.clear();
        cookiePersistor.clear();
    }
}
